package com.study.java2.oauth.config;

import com.study.java2.oauth.service.JdbcUserDetailsServiceImpl;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 创建自定义授权处理类，继承AbstractTokenGranter类然后重写getOAuth2Authentication方法
 */
public class MyAuthenticationTokenGranter extends AbstractTokenGranter {
    private  static final String GRANT_TYPE = "sms_code";//自定义授权码
    private UserDetailsService userDetailsService;

    public MyAuthenticationTokenGranter(AuthorizationServerEndpointsConfigurer endpoints,
                                        UserDetailsService userDetailsService){
        this(endpoints.getTokenServices(), endpoints.getClientDetailsService(), endpoints.getOAuth2RequestFactory(), GRANT_TYPE);
        this.userDetailsService=userDetailsService;
    }

    public MyAuthenticationTokenGranter(AuthorizationServerTokenServices tokenServices,
                                        ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, String grantType) {
        super(tokenServices, clientDetailsService, requestFactory, grantType);
    }

    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
        String mobile = parameters.get("mobile");
        String smsCode = parameters.get("sms_code");//手机验证码，暂时没开发验证码发送功能，就只用手机号码验证
        //根据手机号码获取用户信息
        JdbcUserDetailsServiceImpl jdbcUserDetailsService = (JdbcUserDetailsServiceImpl) userDetailsService;
        UserDetails userDetails = jdbcUserDetailsService.loadUserByMobile(mobile);
        //preAuthenticationChecks.check(userDetails);
        Authentication userAuth = new UsernamePasswordAuthenticationToken(userDetails, null);
        //我们不需要使用AuthenticationManager认证userAuth，直接根据userAuth创建OAuth2Request
        OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
        return new OAuth2Authentication(storedOAuth2Request, userAuth);
    }
}
